package com.studentmanagement.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.studentmanagement.model.User;
import com.studentmanagement.service.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 显示首页
     */
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    /**
     * 处理登录请求
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session,
                        Model model) {
        // 验证用户登录
        User user = userService.validateUser(username, password);

        if (user != null) {
            // 登录成功，将用户信息存入会话
            session.setAttribute("user", user);

            // 重定向到控制面板
            return "redirect:/dashboard";
        } else {
            // 登录失败，设置错误消息
            model.addAttribute("error", "用户名或密码错误");

            // 返回登录页面
            return "login";
        }
    }

    /**
     * 显示注册页面
     */
    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    /**
     * 处理注册请求
     */
    @PostMapping("/register")
    public String register(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("confirmPassword") String confirmPassword,
                           Model model) {
        // 验证密码是否一致
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "register";
        }

        // 注册用户
        boolean success = userService.registerUser(username, password, "USER");

        if (success) {
            // 注册成功，重定向到登录页面
            model.addAttribute("message", "注册成功，请登录");
            return "login";
        } else {
            // 注册失败，设置错误消息
            model.addAttribute("error", "用户名已存在或注册失败");
            return "register";
        }
    }

    /**
     * 处理注销请求
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 使会话失效
        session.invalidate();

        // 重定向到登录页面
        return "redirect:/login";
    }

    /**
     * 显示控制面板
     */
    @GetMapping("/dashboard")
    public String dashboard() {
        return "dashboard";
    }
}